/**
 * \file Pit.cc
 * \brief Programmable interval timer
 * \author Corey Tabaka
 */

/*
   Copyright 2006 Corey Tabaka

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include <platform/Pit.h>
#include <Sync.h>
#include <i386/io.h>

/*
 * Cached frequency divisor.
 */
static uint16 divisor;

/*
 * Interrupt mutex.
 */
static InterruptLock pitLock;

#define INTERNAL_FREQ 1193182L

extern bool inVMware;

void Pit::initialize(void) {
	if (inVMware) {
		//setDivisor(INTERNAL_FREQ / 1000);
		setDivisor(INTERNAL_FREQ / 200);
		//setDivisor(INTERNAL_FREQ / 5000);
	} else {
		//setDivisor(32);
		//setDivisor(1);
		setDivisor(INTERNAL_FREQ / 200);
		//setDivisor(INTERNAL_FREQ / 5000);
		//setDivisor(INTERNAL_FREQ / 3000);
	}
}

void Pit::setDivisor(uint16 div) {
	pitLock.lock();
	
	divisor = div;
	
	/*
	 * Setup the Programmable Interval Timer
	 * Timer 0, mode 3, internal freq / 1 ... internal freq = 1193182L
	 */
	outp(0x43, 0x34); // timer/mode select, freq devisor LSB followed by MSB
	outp(0x40, divisor & 0xff); // LSB
	outp(0x40, divisor >> 8); // MSB
	
	pitLock.unlock();
}

uint32 Pit::getFrequency(void) {
	return INTERNAL_FREQ / divisor;
}
